package com.sportschain.app.core.network;

import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.lzy.okgo.convert.Converter;

import org.json.JSONObject;

import okhttp3.Response;

public class JsonConvert implements Converter<JSONObject> {
    @Override
    public JSONObject convertResponse(Response response) throws Throwable {
        if (response.body() == null) {
            throw new EmptyDataException("response.body() == null");
        }

        JSONObject jsonObject = new JSONObject(response.body().string());

        // 获取statusCode
        int statusCode;
        try {
            statusCode = jsonObject.getInt("status");
        } catch (Exception e) {
            statusCode = 100;
        }
        if (statusCode != 200) {
            throw new IllegalStateException(String.valueOf(statusCode));
        }

        LogUtils.d("json", jsonObject.toString());
        String dataStr = jsonObject.optString("data");
        if (!TextUtils.isEmpty(dataStr)) {
            return new JSONObject(dataStr);
        } else {
            throw new EmptyDataException("dataStr is empty");
        }
    }
}
